<?php
/**
 *
 * PHP versions 5
 *
 * Copyright (C)
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
 * Fundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 * @author Bastian Schröder <bs@chemanet.de>
 * @version 2007-08-06
 * @package rail
 */

define( 'RAILADMIN_DATABASES', $_GET['db'] );
$_SESSION['mysql_db'] = RAILADMIN_DATABASES;
$messages = array();

// connect to MySQL from SESSION
$mysqli = new mysqli( $_SESSION['mysql_host'], $_SESSION['mysql_user'], $_SESSION['mysql_passwd'] );

unset($_SESSION['LOGIN']);

/* ------------------------------------- builder -------------------------------------- */
try{
	// create new MySQL databases if requested
	if( isset($_GET['adddb']) ){
		// select all MySQL databases
		$data = $mysqli->query( 'SHOW DATABASES' );
		while( $data_row = $data->fetch_assoc() ){
			if( $data_row["Database"] == RAILADMIN_DATABASES )
				throw new Exception( 'MySQL: Die Datenbank \'' . RAILADMIN_DATABASES . '\' existiert bereits.' );
		}

		$mysqli->query( 'CREATE DATABASE ' . RAILADMIN_DATABASES );
		array_push( $messages, array( 'type' => 'info', 'messages' => 'Neue MySQL-Datenbank wurde erzeugt.' ) );
	}

	$mysqli->select_db( RAILADMIN_DATABASES );
	$rail_tables = array( 'objects', 'objects_attributes', 'objects_relations', 'objects_documents' );

	// check wheater one ore more rail tables allready exists
	$data = $mysqli->query( 'SHOW TABLES' );
	while( $data_row = $data->fetch_assoc() ){
		if( in_array($data_row[ 'Tables_in_' . RAILADMIN_DATABASES ], $rail_tables) )
			throw new Exception( "Mindestens eine rail MySQL-Tabelle existiert bereits." );
	}

	// create all MySQL rail tables
	$mysqli->query( "CREATE TABLE `objects` (
					  `id` int(11) NOT NULL AUTO_INCREMENT,
					  `type` varchar(255) NOT NULL,
					  `environment` int(11) NOT NULL,
					  `user` int(11) NOT NULL,
					  `group` int(11) NOT NULL,
					  `mode` varchar(255) NOT NULL,
					  PRIMARY KEY (`id`),
					  KEY `environment` (`environment`)
					) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci" );

	$mysqli->query( "CREATE TABLE `objects_attributes` (
					  `object` int(11) NOT NULL,
					  `attribute` varchar(255) collate utf8_unicode_ci NOT NULL,
					  `value` varchar(255) collate utf8_unicode_ci NOT NULL,
					  KEY `object` (`object`),
					  KEY `attribute` (`attribute`)
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci" );

	$mysqli->query( "CREATE TABLE `objects_relations` (
					  `object1` int(11) NOT NULL,
					  `object2` int(11) NOT NULL,
					  `type` varchar(255) collate utf8_unicode_ci NOT NULL,
					  KEY `object1` (`object1`),
					  KEY `object2` (`object2`)
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;" );

	$mysqli->query( "CREATE TABLE `objects_documents` (
					  `id` int(11) NOT NULL AUTO_INCREMENT,
					  `md5` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
					  `content` longblob NOT NULL,
					  PRIMARY KEY (`id`)
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci" );

	// check wheater all tables created
	$data = $mysqli->query( 'SHOW TABLES' );
	$i = 0;
	while( $data_row = $data->fetch_assoc() ){
		if( in_array($data_row[ 'Tables_in_' . RAILADMIN_DATABASES ], $rail_tables ) )
			$i ++;
	}
	if( $i != count($rail_tables) )
		throw new Exception( "Die rail MySQL Tabellen konnten nicht angelegt werden." );

	// all rail tables has created
	array_push( $messages, array( 'type' => 'info', 'messages' => 'Alle MySQL-Tabellen für das rail wurden erzeugt.' ) );

	define( 'TIMESTAMP', time() );

	$root_id = create_rail_object( "root", "RAIL_ROOT" );
	$mysqli->query( "INSERT INTO objects_attributes (`object`,`attribute`,`value`) VALUES ('$root_id','RAIL_VERSION','" . PHPrail_VERSION . '-' . PHPrail_REVISION . "')" );

	$users_id = create_rail_object( "users", "RAIL_CONTAINER", $root_id );
	$mysqli->query( "INSERT INTO objects_relations (`object1`,`object2`,`type`) VALUES ('$root_id','$users_id','RAIL_USER_CONTAINER')" );

	$users_root_id = create_rail_object( "root", "RAIL_USER", $users_id );
	$mysqli->query( "INSERT INTO objects_attributes (`object`,`attribute`,`value`) VALUES ('$users_root_id','RAIL_PASSWD','" . md5("rail") . "')" );

	$users_guest_id = create_rail_object( "guest", "RAIL_USER", $users_id );
	$mysqli->query( "INSERT INTO objects_attributes (`object`,`attribute`,`value`) VALUES ('$users_guest_id','RAIL_PASSWD','" . md5("guest") . "')" );

	$groups_id = create_rail_object( "groups", "RAIL_CONTAINER", $root_id );
	$mysqli->query( "INSERT INTO objects_relations (`object1`,`object2`,`type`) VALUES ('$root_id','$groups_id','RAIL_GROUP_CONTAINER')" );

	$groups_root_id = create_rail_object( "root", "RAIL_GROUP", $groups_id );
	$groups_users_id = create_rail_object( "users", "RAIL_GROUP", $groups_id );

	// set user, group and mode filed for all added objects
	$mysqli->query( "UPDATE objects SET `user`='$users_root_id',`group`='$groups_root_id',`mode`='" . mode_decode(644) ."' WHERE `id`='$root_id' LIMIT 1" );
	$mysqli->query( "UPDATE objects SET `user`='$users_root_id',`group`='$groups_root_id',`mode`='" . mode_decode(640) ."' WHERE `id`='$users_id' LIMIT 1" );
	$mysqli->query( "UPDATE objects SET `user`='$users_root_id',`group`='$groups_root_id',`mode`='" . mode_decode(640) ."' WHERE `id`='$users_root_id' LIMIT 1" );
	$mysqli->query( "UPDATE objects SET `user`='$users_guest_id',`group`='$groups_users_id',`mode`='" . mode_decode(640) ."' WHERE `id`='$users_guest_id' LIMIT 1" );
	$mysqli->query( "UPDATE objects SET `user`='$users_root_id',`group`='$groups_root_id',`mode`='" . mode_decode(640) ."' WHERE `id`='$groups_id' LIMIT 1" );
	$mysqli->query( "UPDATE objects SET `user`='$users_root_id',`group`='$groups_root_id',`mode`='" . mode_decode(640) ."' WHERE `id`='$groups_root_id' LIMIT 1" );
	$mysqli->query( "UPDATE objects SET `user`='$users_root_id',`group`='$groups_root_id',`mode`='" . mode_decode(640) ."' WHERE `id`='$groups_users_id' LIMIT 1" );

	array_push( $messages, array( 'type' => 'info', 'messages' => 'Ein rail wurde aufgebaut.' ) );

	header( 'Location: index.php?tpl=portal' );
}
catch( Exception $e ){
	array_push( $messages, array( 'type' => 'error', 'messages' => 'Das rail konnte nicht erzeugt werden: ' . $e->getMessage() ) );
}


/* -------------------------------------- Display ------------------------------------- */
// display all messages
$template->assign( 'messages', $messages );


/* ------------------------------------- functions ------------------------------------ */
function create_rail_object( $pName, $pType, $pEnvironment = 0, $pUser = "", $pGroup = "", $pMode = "640" ){
	global $mysqli;
	$rail_id = 0;

	// insert into mysql objects and add OBJ_NAME attrbute
	$mysqli->query( "INSERT INTO objects ( `type`, `environment`, `user`, `group`, `mode` ) VALUES ('$pType', '$pEnvironment', '$pUser', '$pGroup', '$pMode')" );
	$data = $mysqli->query( "SELECT `id` FROM objects WHERE `type`='$pType' ORDER BY `id` DESC LIMIT 1" )->fetch_assoc();
	$rail_id = $data["id"];
	$mysqli->query( "INSERT INTO objects_attributes (`object`,`attribute`,`value`) VALUES ('$rail_id','OBJ_NAME','$pName')" );

	//  Add OBJ_TIME_CREATE and OBJ_TIME_LASTWRITE attributes
	$mysqli->query( "INSERT INTO objects_attributes (`object`,`attribute`,`value`) VALUES ('$rail_id','OBJ_TIME_CREATE','". TIMESTAMP . "')" );
	$mysqli->query( "INSERT INTO objects_attributes (`object`,`attribute`,`value`) VALUES ('$rail_id','OBJ_TIME_LASTWRITE','". TIMESTAMP . "')" );

	return $rail_id;
}

function mode_decode( $pMode ){
	return  substr( decbin( substr($pMode, 0, 1) ) . "000", 0, 3 ) .
			substr( decbin( substr($pMode, 1, 1) ) . "000", 0, 3 ) .
			substr( decbin( substr($pMode, 2, 1) ) . "000", 0, 3 );
}

?>